package net.caixiaomi.info.shopkeeper;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by mac on 2018/11/14.
 */

public class PhotoImpl {

    private OSS oss;
    private Context mContext;
    // 这个是外网域名的后半部分(外网域名 = bucket.endpoint)，根据你申请的填一般是"http://oss-cn-hangzhou.aliyuncs.com"
    public static  String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

    public static String accessKeyId = "**********";  // 你申请的accessKeyId
    public static  String accessKeySecret = "**********"; // accessKeySecret
    public static  String testBucket = "*****";  // 这个就是你申请的bucket名称
    public static  String uploadFilePath="";  //这个路径是你要上传的文件的路径（本地）
//    private String uploadObject = getPhotoFileName();  // 这个是你要上传到OSS的文件路径，加入想上传到文件夹则前面加上****/****形式的路径即可
    public static String uploadObject="";

    public void init(Context context,callBack callBack){
        mContext=context;
        mCallBack=callBack;
        initOSS();
    }

    /**初始化阿里云*/
    private void initOSS() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(mContext, endpoint, credentialProvider, conf);
    }

    /**
     *
     * @return 图片上传到阿里云的路径
     */
    public String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        return "img" + "/" + dateFormat.format(date) + ".webp";
    }

    public void loadImg(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                asyncPutObjectFromLocalFile(uploadObject,uploadFilePath);
            }
        }).start();
    }

    /**
     * 从本地文件上传，使用非阻塞的异步接口
     * @param uploadObject 这个是你要上传到OSS的文件路径，加入想上传到文件夹则前面加上xxx/xxx形式的路径即可
     * @param locationPath  这个路径是你要上传的文件的路径（本地）
     */
    public void asyncPutObjectFromLocalFile(final String uploadObject, String locationPath) {

        // 指定数据类型，没有指定会自动根据后缀名判断
//        ObjectMetadata objectMeta = new ObjectMetadata();
//        objectMeta.setContentType("image/jpeg");

        /**
         * 构造上传请求
         * oss 配置
         * testBucket 申请的Bucket名称
         * uploadObject  这个是你要上传到OSS的文件路径（一般是  "img" + "/" + "当前时间" + ".jpg";）
         * path  这个路径是你要上传的文件的路径（本地）
         */
        PutObjectRequest put = new PutObjectRequest(testBucket, uploadObject, locationPath);
//        put.setMetadata(objectMeta);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // 在这里可以实现进度条展现功能
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.e("PutObject", "上传图片成功");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                mCallBack.onSuccess("");
//                successPath.add(uploadObject);  // 把当前上传图片成功的阿里云路径添加到集合
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());

                }
                mCallBack.onFailure("图片上传失败，请重新上传");
//                ToastUtils.showShort(mContext, "图片上传失败，请重新上传");
            }
        });
    }

    callBack mCallBack;

    public interface callBack{
        public void onSuccess(String path);
        public void onFailure(String msg);
    }
}
